<template>
	<view class="container">
		<!-- Header Section -->
		<view class="header-section">
			<view class="user-info">
				<text class="username">{{refName}}</text>
				<!-- <text class="department">山东黄河河务局信息中心办公室</text> -->
			</view>
		</view>

		<view class="main-content">
			<view class="card-container">
				<!-- News Information Card -->
				<view class="info-card news-card" @click="navTo('/pages/sys/new/home')">
					<view class="icon-box">
						<image src="/static/aidex/images/new.png" class="card-icon"></image>
					</view>
					<text class="card-text green-text">新闻资讯</text>
				</view>

				<!-- To-do Tasks Card -->
				<view class="info-card todo-card" @click="navTo('/pages/sys/msg/list-item')">
					<view class="icon-box">
						<image src="/static/aidex/images/msg.png" class="card-icon"></image>
					</view>
					<text class="card-text blue-text">待办任务 ({{todoCount}})</text>
				</view>
			</view>

			<u-swiper style="margin: -10rpx 0rpx 20rpx 0rpx; border-radius: 5px;" :height="270" :list="imgList"
				:title="false" @click="imgListClick"></u-swiper>

			<!-- News List Section -->

				<div style="background-color: white;width: 100%;">
					<view class="news-tabs">
						<view class="tab-item" :class="{ 'active-tab': position === 'zytz' }"
							@click="switchTab('zytz')">重要通知</view>
						<view class="tab-item" :class="{ 'active-tab': position === 'jrfw' }"
							@click="switchTab('jrfw')">近日发文</view>
						<view class="tab-item" :class="{ 'active-tab': position === 'jrsw' }"
							@click="switchTab('jrsw')">近日收文</view>
						<view class="tab-item" :class="{ 'active-tab': position === 'gsgg' }"
							@click="switchTab('gsgg')">公示公告</view>
					</view>
				</div>
				<scroll-view scroll-y style="height: 70vh;" @scrolltolower="loadMore">
				<view>
					<div style="background-color: white !important;width: 100%" v-for="(item, index) in newsList"
						:key="index">
						<view class="news-item">
							<text class="news-title">{{item.title}}</text>
							<view class="news-meta">
								<text class="news-source">{{item.source}}</text>
								<text class="news-date">{{item.date}}</text>
								<button style="border: none !important;" class="detail-button blue-text"
									@click="viewArticleDetail(item)">详情</button>
							</view>
						</view>
					</div>
				</view>
				</scroll-view>
		</view>

		<!-- 文件列表弹窗 -->
		<view v-if="showFileListDialog" class="file-list-dialog-overlay" @click.self="showFileListDialog = false">
			<view class="file-list-dialog-content">
				<view class="dialog-title">请选择文件</view>
				<scroll-view scroll-y class="file-list-scroll">
					<view class="file-item" v-for="(file, fileIdx) in currentFileList" :key="fileIdx"
						@click="openFilePreview(file)">
						<text class="file-name">{{ file.fileName }}</text>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>
<script>
	import HeadNavBar from '@/components/headnavbar/index';
	import {
		checkLogin
	} from '@/common/auth.js';
	import config from '@/common/config.js';
	/**
	 * Copyright (c) 2013-Now http://aidex.vip All rights reserved.
	 */
	export default {
		components: {
			HeadNavBar
		},
		data() {
			return {
				refName: '超级管理员',
				userName: '超级管理员',
				show: false,
				head: '/static/aidex/images/images/head.png',
				position: 'zytz', // 默认选中"重要通知"标签
				imgList: [{
					image: '/static/aidex/images/bg1.jpg'
				}, {
					image: '/static/aidex/images/bg2.jpg'
				}, {
					image: '/static/aidex/images/bg3.jpg'
				}],
				todoCount: 0, // 初始化为0
				newsList: [], // 初始化为空数组，等待API数据
				queryParams: {
					pageNum: 1,
					pageSize: 5,
					categoryId: '',
					siteCode: 'main',
					__sid: '',
					__ajax: 'json'
				},
				showFileListDialog: false, // 控制文件列表弹窗显示
				currentFileList: [] // 存储当前文件的文件列表
			};
		},
		onShow() {
			this.userName = uni.getStorageSync('userName') || '登录失败';
			this.refName = uni.getStorageSync('refName') || '登录失败';
		},
		onLoad() {
			// 获取Token
			this.getTokenFromUrl();
			//  this.getSessionIDByHwId('414796')
			if (!checkLogin()) {
				return
			}
		},
		methods: {
			// 从上一页url中获取token值
			getTokenFromUrl() {
				// 425426	办公室收文
				// 419413	郝文红
				// 431963            王洁
				// 415684  	张沪予
				// 428898   王新波
				// 111111
				//418750 管理员
				//429022
				//跳过token跳转
				// this.getSessionIDByHwId(430427);
				const params = new URLSearchParams(window.location.search);
				var token = params.get('token') || null;
				//	alert(token)
				if (!token) {
					// 跳转到无效token提示页
					uni.redirectTo({
						url: '/pages/sys/invalid-token'
					});
					return;
				}
				// 通过Token获取Id
				this.getHwIdByToken(token);
			},

			// 根据Token获取黄委Id
			getHwIdByToken(token) {
				//	alert("token:" + token)
				//强制使用某一个id
				// this.getShdjLoginId(415935);
				// 下面代码是动态获取根据token
				this.$u.api.getHwIdByToken({
					'access_token': token
				}).then(res => {
					// alert("黄委返回=" + JSON.stringify(res));
					if (res.code === 200) {
						var hwId = res.data.id;
						// alert(JSON.stringify('根据Token获取到的Id='+id))
						this.getSessionIDByHwId(hwId);
					} else {
						// 跳转到无效token提示页
						uni.redirectTo({
							url: '/pages/sys/invalid-token'
						});
						return;
					}
				}).catch(error => {
					uni.showToast({
						title: '获取黄委接口失败',
						icon: 'none'
					});
				})

			},

			// 根据黄委Id获取sessionid
			getSessionIDByHwId(hwId) {
				this.$u.api.getSessionIDByHwId({
					'lCode': hwId,
					'__ajax': 'json',
					'_t': Date.now()
				}).then(res => {
					// alert("获取sessionid接口：" + JSON.stringify(res));
					if (res.result === true || res.result === 'true') {
						uni.setStorageSync('userName', res.user.userName);
						uni.setStorageSync('refName', res.user.refName);
						this.userName = res.user.userName;
						this.refName = res.user.refName;
						uni.setStorageSync('sessionid', res.sessionid);
						uni.setStorageSync('corpCode_', res.user.corpCode_);
						debugger
						// alert('sessionId=' + res.sessionid)
						this.loadTodoCount();
						this.loadArticleList();
					} else {
						uni.setStorageSync('userName', '');
						uni.setStorageSync('refName', '');
						uni.setStorageSync('sessionid', '');
						uni.showToast({
							title: '获取sessionid失败',
							icon: 'none'
						});
					}
				}).catch(error => {
					uni.showToast({
						title: '获取sessionid接口失败',
						icon: 'none'
					});
				})
			},

			// 加载待办任务数量
			async loadTodoCount() {
				try {
					const params = {
						__sid: uni.getStorageSync('sessionid'),
						__ajax: 'json',
						status: 1
					};
					const res = await this.$u.api.getDaibanList(params);
					if (res && res.code === 1 && res.data) {
						this.todoCount = res.data.count;
					}
				} catch (error) {
					console.error('获取待办任务数量失败:', error);
				}
			},

			// 加载文章列表
			async loadArticleList(isLoadMore = false) {
				try {
					const cateCodeMap = {
						'zytz': 'C20', // 重要通知
						'gsgg': 'C21' // 时政信息
					};
					const cateCodes = cateCodeMap[this.position] || '';
					const params = {
						...this.queryParams,
						__sid: uni.getStorageSync('sessionid'),
						position: this.position,
						__ajax: 'json',
						type: 1,
						cateCodes
					};

					let res;
					if (this.position === 'jrfw' || this.position === 'jrsw') {
						// 近日发文、近日收文调用老接口
						res = await this.$u.api.getArticleListOld(params);
					} else {
						// 其他类型调用新接口
						res = await this.$u.api.getArticleList(params);
					}
					if (this.position === 'jrfw' || this.position === 'jrsw') {
							const result = res;
							const newList = result.data.list.map(item => ({
								title: item.contentTitle,
								source: item.channelName,
								date: item.onlineDate,
								channelType: item.channelType,
								fileUrlList: item.fileUrlList || [],
								id: (item.fileUrlList && item.fileUrlList[0] && item.fileUrlList[0].id) || ''
							}));
							if (isLoadMore) {
								this.newsList = this.newsList.concat(newList);
							} else {
								this.newsList = newList;
							}
					}else{
					const result = res.resultEntity || result;
					if (result.code === 1 ) {

							const newList = result.data.list.map(item => ({
								title: item.title,
								source: item.category && item.category.categoryName ? item.category.categoryName : '',
								date: item.onlineDate,
								id: item.id,
								webUrl: item.url,
								image: item.image || ''
							}));
							if (isLoadMore) {
								this.newsList = this.newsList.concat(newList);
							} else {
								this.newsList = newList;
							}
						
					}
					}
				} catch (error) {
					console.error('加载文章列表失败:', error);
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				}
			},
			// 查看文章详情
			viewArticleDetail(item) {
				if ((this.position === 'jrfw' || this.position === 'jrsw') && item.channelType === 'file') {
					if (item.fileUrlList && item.fileUrlList.length > 0) {
						if (item.fileUrlList.length > 1) {
							this.currentFileList = item.fileUrlList;
							this.showFileListDialog = true;
						} else {
							this.openFilePreview(item.fileUrlList[0], item.title);
						}
					} else {
						uni.showToast({
							title: '没有找到可预览的文件',
							icon: 'none'
						});
					}
				} else {
					// 其他类型走原有逻辑
					uni.navigateTo({
						url: `/pages/sys/new/form?id=${encodeURIComponent(item.id)}`
					});
				}
			},
			openFilePreview(file, defaultTitle = '') {
				const timestamp = new Date().getTime();
				const encodedUrl = encodeURIComponent(config.importantBaseUrl  + file.fileUrl);
				const url = `https://xdoc.sdhwj.com/view?mtime=${timestamp}&src=${encodedUrl}`;
				window.open(url, '_blank');
				this.showFileListDialog = false;
			},
			navTo(url) {
				uni.navigateTo({
					url: url
				});
			},
			switchTab(tab) {
				let tabNameMap = {
					'zytz': '重要通知',
					'jrfw': '重要信息',
					'jrsw': '部委信息',
					'szxx': '时政信息'
				};
				const categoryName = tabNameMap[tab] || '';
				this.position = tab;
				this.queryParams.categoryId = tab;
				this.newsList = [];
				this.queryParams.pageNum = 1;
				this.loadArticleList();
			},
			imgListClick(index) {
				console.log(`点击了第${index + 1}页图片`)
			},
			itemClick(index) {
				console.log(index);
			},
			// 分页加载更多
			loadMore() {
				this.queryParams.pageNum++;
				this.loadArticleList(true);
			}
		}
	};
</script>
<style lang="scss" scoped>
	@import 'index.scss';

	/* 全局样式覆盖 */
	:deep(.u-list-image-wrap) {
		border-radius: 5px !important;
		overflow: hidden;
	}

	.container {
		background-color: #f5f5f5;
		padding-bottom: 20rpx; // 为整个页面容器添加底部内边距
	}

	.header-section {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		background-image: url('/static/aidex/images/bg.jpg');
		background-size: 100% 100%;
		background-position: center;
		background-repeat: no-repeat;
		color: white;
		height: 200rpx;
	}

	.user-info {
		display: flex;
		flex-direction: column;

		.username {
			font-size: 36rpx;
			font-weight: bold;
			margin-bottom: 5rpx;
		}

		.department {
			font-size: 24rpx;
			opacity: 0.8;
		}
	}

	.weather-info {
		display: flex;
		flex-direction: column;
		align-items: center;

		.weather-icon {
			width: 60rpx;
			height: 60rpx;
			margin-bottom: 5rpx;
		}

		.temperature {
			font-size: 28rpx;
		}
	}

	.u-swiper-wrap {
		margin: 0 0 30rpx 0;
		border-radius: 10rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	}

	.main-content {
		padding: 0 20rpx;
	}

	.card-container {
		display: flex;
		justify-content: space-between;
		margin-bottom: 30rpx;
		margin-top: 20rpx;
	}

	.info-card {
		width: 48%;
		height: 94rpx;
		border-radius: 5px;
		display: flex;
		align-items: center;
		padding: 0 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	}

	.news-card {
		background: linear-gradient(to right, rgba(140, 206, 189, 1), rgba(214, 229, 235, 0.22));
	}

	.todo-card {
		background: linear-gradient(to right, rgba(75, 154, 196, 0.25), rgba(214, 229, 235, 0.22));
	}

	.icon-box {
		width: 80rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 20rpx;
		border-radius: 50%;
		// background-color: rgba(255, 255, 255,1);
	}

	.card-icon {
		width: 32rpx;
		height: 32rpx;
		margin-right: 10rpx;
	}

	.card-text {
		font-size: 28rpx;
		font-weight: bold;
	}

	.green-text {
		color: #179E7A;
	}

	.blue-text {
		color: #009DFF;
	}

	.news-list-section {
		background-color: white;
		border-radius: 15rpx;
		padding: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		margin-top: 0;
		margin-bottom: 0;
	}

	.news-tabs {
		display: flex;
		justify-content: space-around;
		margin-bottom: 10rpx;
		border-bottom: 1rpx solid #eee;
		padding-bottom: 10rpx;

		.tab-item {
			font-size: 28rpx;
			color: #555555;
			padding: 10rpx 20rpx;
			cursor: pointer;
			margin-top: 10rpx !important;
			position: relative;
			text-align: center;

			&.active-tab {
				color: #009DFF;
				font-weight: bold;

				&::after {
					content: '';
					position: absolute;
					bottom: -10rpx;
					left: 50%;
					transform: translateX(-50%);
					width: 40rpx;
					height: 4rpx;
					background-color: #009DFF;
					border-radius: 2rpx;
				}
			}
		}
	}

	.news-item {
		padding: 30rpx; // 添加顶部内边距，使内容与新闻条目顶部有间距
		border-bottom: 1rpx dashed #eee;
		margin-bottom: 10rpx;

		&:last-child {
			border-bottom: none;
		}

		.news-title {
			font-size: 30rpx;
			color: #000000;
			line-height: 1.4;
			margin-bottom: 10rpx;
		}

		.news-meta {
			margin-top: 20rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 24rpx;
			color: #555555;

			.news-source {
				width: 33.33%;
				margin-right: 20rpx;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				flex-shrink: 1;
				flex-grow: 0;
			}

			.news-date {
				// width: 35%;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				flex-shrink: 1;
				flex-grow: 0;
				text-align: center;
			}

			.detail-button {
				float: right;
				width: 15%;
				background-color: rgba(0, 157, 240, 0.11);
				color: #009DFF;
				border: none !important;
				padding: 8rpx 0rpx;
				font-size: 24rpx;
				margin-right: 0rpx;
				min-width: unset;
				height: unset;
				line-height: unset;
				flex-shrink: 0;
			}

			.uni-button:after {
				border: none !important;
			}

			.detail-button:after {
				border: none !important;
			}
		}
	}

	// 移除或覆盖原有不适用样式
	.workbench-title,
	.toolbar {
		display: none;
	}

	.u-mode-light-info {
		display: none;
	}

	/* File list dialog styles */
	.file-list-dialog-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.6);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 1000;
	}

	.file-list-dialog-content {
		background-color: #fff;
		border-radius: 16rpx;
		width: 80%;
		max-height: 70%;
		display: flex;
		flex-direction: column;
		padding: 30rpx;
	}

	.dialog-title {
		font-size: 34rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
		text-align: center;
		color: #333;
	}

	.file-list-scroll {
		flex: 1;
		max-height: 600rpx;
		/* Limit scroll height */
		margin-bottom: 20rpx;
	}

	.file-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #eee;
		font-size: 30rpx;
		color: #333;
	}

	.file-item:last-child {
		border-bottom: none;
	}

	.file-name {
		flex: 1;
		margin-right: 20rpx;
		white-space: normal;
		overflow: visible;
		text-overflow: clip;
		word-break: break-all;
	}
</style>